//
//  SearchViewController.m
//  cityCar
//
//  Created by yao on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "WebColor.h"
#import "ForumGather.h"
#import "ForumDetailViewController.h"
#import "Car.h"
#import "SearchCarViewController.h"
#import "YRSideViewController.h"
#import "AppDelegate.h"

@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *myTableView;

// 搜索输入的内容
@property(nonatomic, retain)NSString *string;
// 显示在tableView上的内容
@property(nonatomic, retain)NSMutableArray *showArray;
// 标题label
@property(nonatomic, retain)UILabel *headLabel;
// 下拉菜单的View
@property(nonatomic, retain)UIView *pullView;
// 下拉菜单的button
@property(nonatomic, retain)UIButton *button;
// 箭头imageView
@property(nonatomic, retain)UIImageView *arrowsImageView;
// 搜索栏
@property(nonatomic, retain)UISearchBar *searchBar;

@end

@implementation SearchViewController

- (void)dealloc
{
    [_myTableView release];
    [_string release];
    [_showArray release];
    [_headLabel release];
    [_pullView release];
    [_button release];
    [_arrowsImageView release];
    [_searchBar release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.string = [NSString string];
        self.showArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [WebColor whiteSmoke];
    [self setupView];
}

- (void)setupView
{
    CGFloat x = self.view.frame.size.width;
    
    // 顶部标题
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake((x - 80) / 2, 20, 80, 30)];
    [self.view addSubview:headView];
    [headView release];
    
    // 下拉菜单的按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake((x - 130) / 2, 20, 130, 30);
    self.button.tintColor = [WebColor white];
    [self.button addTarget:self action:@selector(pullButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
 
    // 标题
    self.headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.headLabel.text = @"找车系论坛";
    self.headLabel.textColor = [WebColor white];
    self.headLabel.font = [UIFont systemFontOfSize:20];
    self.headLabel.textAlignment = NSTextAlignmentCenter;
    [self.button addSubview:self.headLabel];
    [_headLabel release];
    
    // 箭头imageView
    self.arrowsImageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 30, 30)];
    self.arrowsImageView.image = [UIImage imageNamed:@"iconfont-xiangxia.png"];
    [self.button addSubview:self.arrowsImageView];
    [_arrowsImageView release];

    // 搜索栏
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 60, 250, 40)];
    self.searchBar.placeholder = @"请输入关键字";
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
    [_searchBar release];

    // 下拉菜单
    self.pullView = [[UIView alloc] initWithFrame:CGRectMake((x - 120) / 2, 0, 120, 80)];
    self.pullView.backgroundColor = [WebColor whiteSmoke];
    self.pullView.hidden = YES;
    self.pullView.layer.cornerRadius = 10;
    [self.view addSubview:self.pullView];
    [_pullView release];
    
    NSArray *array = [NSArray arrayWithObjects:@"找车系论坛",@"找地区论坛",@"找综合论坛",@"找车", nil];
    for (int i = 0; i < array.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, i * 20, 120, 20);
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        button.tintColor = [WebColor black];
        [self.pullView addSubview:button];
    }
        
    // 背景图片
    UIImageView *myImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    myImageView.image = [UIImage imageNamed:@"sousuo2.jpg"];
    [self.view addSubview:myImageView];
    [self.view sendSubviewToBack:myImageView];
    [myImageView release];
    
    
    // 显示搜索结果
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 130, 250, self.view.frame.size.height - 140) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.hidden = YES;
    self.myTableView.alpha = 0.8;
    self.myTableView.tag = 20000;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
}

- (void)buttonClicked:(UIButton *)button
{
    self.headLabel.text = button.titleLabel.text;
    self.searchBar.text = nil;
    [self.showArray removeAllObjects];
    [self.myTableView reloadData];
    [self pullButtonClicked:self.button];
}

- (void)pullButtonClicked:(UIButton *)button
{
    
    UIImage *backImage = self.arrowsImageView.image;
    UIImage *image = [UIImage imageNamed:@"iconfont-xiangxia.png"];
    if ([backImage isEqual:image]) {
        self.arrowsImageView.image = [UIImage imageNamed:@"iconfont-xiangshang.png"];
        [UIView transitionWithView:self.pullView duration:0.2 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
            self.pullView.frame = CGRectMake((self.view.frame.size.width - 120) / 2, 50, 120, 80);
            self.pullView.hidden = NO;
        } completion:^(BOOL finished) {
            
        }];

    } else {
        self.arrowsImageView.image = [UIImage imageNamed:@"iconfont-xiangxia.png"];
        [UIView animateWithDuration:1 animations:^{
            self.pullView.frame = CGRectMake((self.view.frame.size.width - 120) / 2, 0, 120, 80);
            self.pullView.hidden = YES;
            
        }];
    }
    
}


// 开始输入
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    self.myTableView.hidden = NO;
    searchBar.showsCancelButton = YES;

}
// 点击取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = nil;
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    YRSideViewController *sideViewController = [delegate sideViewController];
    [sideViewController hideSideViewController:true];
    
    self.myTableView.hidden = YES;
    searchBar.showsCancelButton = NO;
    
}

#pragma mark - UISearchBarDelegate 协议
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.showArray removeAllObjects];
    NSArray *achieveArray = [self achieveDate];
    if ([self.headLabel.text isEqualToString:@"找车"]) {
        for (Car *car in achieveArray) {
            NSRange range =[car.name rangeOfString:searchText];
            if (range.length != 0) {
                [self.showArray addObject:car];
                NSLog(@"找车结果:%@", car.name);
            }
            [self.myTableView reloadData];
        }
    } else {
        for (ForumGather *forum in achieveArray) {
            NSRange range = [forum.name rangeOfString:searchText];
            if (range.length != 0) {
                [self.showArray addObject:forum];
                NSLog(@"搜索结果：%@", forum.name);
            }
            [self.myTableView reloadData];
        }        
    }
}
// 从本地获取
- (NSArray *)achieveDate
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths lastObject];
    NSArray *achieveArray = [NSArray array];
    if ([self.headLabel.text isEqualToString:@"找车系论坛"]) {
        NSString *carPath = [documentPath stringByAppendingPathComponent:@"car.aaa"];
        achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:carPath];
    } else if ([self.headLabel.text isEqualToString:@"找地区论坛"]) {
        NSString *areaPath = [documentPath stringByAppendingPathComponent:@"area.aaa"];
        achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:areaPath];
    } else if ([self.headLabel.text isEqualToString:@"找综合论坛"]) {
        NSString *areaPath = [documentPath stringByAppendingPathComponent:@"composite.aaa"];
        achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:areaPath];
    } else if ([self.headLabel.text isEqualToString:@"找车"]) {
        NSString *areaPath = [documentPath stringByAppendingPathComponent:@"searchCar.aaa"];
        achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:areaPath];
    }
    
    return achieveArray;
    
}

#pragma mark - tableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.showArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"]autorelease];
    }
    ForumGather *forum = [self.showArray objectAtIndex:indexPath.row];
    cell.textLabel.text = forum.name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.headLabel.text isEqualToString:@"找车"]) {
        SearchCarViewController *seaCarVC = [[SearchCarViewController alloc] init];
        seaCarVC.car = [self.showArray objectAtIndex:indexPath.row];
        [self presentViewController:seaCarVC animated:YES completion:^{
            
        }];
    } else {
        
        ForumDetailViewController *forumDerailVC = [[ForumDetailViewController alloc] init];
        ForumGather *forum = [self.showArray objectAtIndex:indexPath.row];
        forumDerailVC.string = forum.Id;
        forumDerailVC.dic = @{@"Name": forum.name};
        [self presentViewController:forumDerailVC animated:YES completion:^{
            
        }];
    }
}

// 滚动scrollView触发的方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
